/*
 * HSM Proxy Project.
 * Copyright (C) 2013 Frank Cornelis.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.model.admin;

import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.ejb3.annotation.SecurityDomain;

import be.fedict.hsm.entity.AdministratorEntity;
import be.fedict.hsm.model.security.AdministratorRoles;
import be.fedict.hsm.model.security.AdministratorSecurityDomain;
import be.fedict.hsm.model.security.JBossSecurityManagerBean;

@Stateless
@SecurityDomain(AdministratorSecurityDomain.NAME)
@RolesAllowed(AdministratorRoles.ADMINISTRATOR)
public class PrivilegesManagerBean {

	@PersistenceContext
	private EntityManager entityManager;

	@EJB
	private JBossSecurityManagerBean securityManagerBean;

	public List<AdministratorEntity> getList() {
		return AdministratorEntity.getList(this.entityManager);
	}

	/**
	 * Removes a given administrator. When you remove the current and only
	 * administrator, it will be directly re-added by the JAAS login module.
	 * 
	 * @param administrator
	 */
	public void removeAdministrator(AdministratorEntity administrator) {
		AdministratorEntity administratorEntity = this.entityManager.find(
				AdministratorEntity.class, administrator.getId());
		this.securityManagerBean.flushAdministratorCache(administratorEntity
				.getId());
		this.entityManager.remove(administratorEntity);
	}

	public void approveAdministrator(AdministratorEntity administrator) {
		AdministratorEntity administratorEntity = this.entityManager.find(
				AdministratorEntity.class, administrator.getId());
		this.securityManagerBean.flushAdministratorCache(administratorEntity
				.getId());
		administratorEntity.setPending(false);
	}
}
